package com.tianya.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianya.domain.dto.MessageQueryDTO;
import com.tianya.domain.dto.MessageSendDTO;
import com.tianya.domain.entity.Message;
import com.tianya.domain.vo.MessageVO;
import com.tianya.domain.vo.PageResultVO;
import com.tianya.domain.vo.UnreadCountVO;
import com.tianya.mapper.MessageMapper;
import com.tianya.service.MessageService;
import com.tianya.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserService userService;

    @Override
    public PageResultVO<MessageVO> getInboxMessages(Long userId, MessageQueryDTO queryDTO) {
        // 创建分页对象
        Page<MessageVO> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

        // 调用Mapper查询
        page = (Page<MessageVO>) messageMapper.selectInboxMessages(
                page,
                userId,
                queryDTO.getKeyword(),
                queryDTO.getIsRead());

        // 处理查询结果，填充额外信息
        List<MessageVO> records = page.getRecords();
        if (records != null && !records.isEmpty()) {
            records = records.stream().map(this::processMessageVO).collect(Collectors.toList());
        }

        // 构建返回结果
        return new PageResultVO<>(
                 page.getTotal(),
                records
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean sendMessage(Long userId, MessageSendDTO messageDTO) {
        // 获取发送者信息
        var sender = userService.getById(userId);
        if (sender == null) {
            throw new RuntimeException("发送者不存在");
        }

        // 获取接收者信息
        var receiver = userService.getById(messageDTO.getReceiverId());
        if (receiver == null) {
            throw new RuntimeException("接收者不存在");
        }
        // 构建消息实体
        Message message = Message.builder()
                .title(messageDTO.getTitle())
                .content(messageDTO.getContent())
                .senderId(userId)
                .senderName(sender.getName())
                .senderRole(sender.getRole())
                .receiverId(messageDTO.getReceiverId())
                .receiverName(receiver.getName())
                .receiverRole(receiver.getRole())
                .isRead(false)
                .replyToId(messageDTO.getReplyToId())
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .isDeleted(false)
                .build();

        // 保存消息
        return save(message);
    }

    @Override
    public Boolean markAsRead(Long messageId, Long userId) {
        // 构建更新条件
        LambdaUpdateWrapper<Message> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Message::getMessageId, messageId)
                .eq(Message::getReceiverId, userId)
                .eq(Message::getIsDeleted, false)
                .set(Message::getIsRead, true)
                .set(Message::getUpdatedAt, LocalDateTime.now());

        // 执行更新
        return update(updateWrapper);
    }

    @Override
    public Boolean deleteMessage(Long messageId, Long userId) {
        // 构建更新条件
        LambdaUpdateWrapper<Message> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Message::getMessageId, messageId)
                .and(wrapper -> wrapper
                        .eq(Message::getSenderId, userId)
                        .or()
                        .eq(Message::getReceiverId, userId))
                .eq(Message::getIsDeleted, false)
                .set(Message::getIsDeleted, true)
                .set(Message::getUpdatedAt, LocalDateTime.now());

        // 执行逻辑删除
        return update(updateWrapper);
    }

    @Override
    public UnreadCountVO getUnreadCount(Long userId) {
        // 查询未读消息数量
        Long count = messageMapper.countUnreadMessages(userId);

        // 构建返回结果
        return UnreadCountVO.builder()
                .count(count)
                .build();
    }

    @Override
    public List<MessageVO> getMessageHistory(Long userId, Long otherUserId) {
        // 查询消息历史
        List<MessageVO> messages = messageMapper.selectMessageHistory(userId, otherUserId);

        // 处理消息，填充额外信息
        if (messages != null && !messages.isEmpty()) {
            messages = messages.stream().map(this::processMessageVO).collect(Collectors.toList());

            // 标记所有消息为已读
            List<Long> messageIds = messages.stream()
                    .filter(msg -> msg.getReceiverId().equals(userId) && !msg.getIsRead())
                    .map(MessageVO::getMessageId)
                    .collect(Collectors.toList());

            if (!messageIds.isEmpty()) {
                LambdaUpdateWrapper<Message> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.in(Message::getMessageId, messageIds)
                        .set(Message::getIsRead, true)
                        .set(Message::getUpdatedAt, LocalDateTime.now());
                update(updateWrapper);
            }
        }

        return messages != null ? messages : new ArrayList<>();
    }

    /**
     * 处理消息VO，填充额外信息
     * @param messageVO 消息VO
     * @return 处理后的消息VO
     */
    private MessageVO processMessageVO(MessageVO messageVO) {
        if (messageVO == null) {
            return null;
        }

        // 设置时间显示
        messageVO.setTimeAgo(formatTimeAgo(messageVO.getCreatedAt()));

        // 设置角色名称
        messageVO.setSenderRoleName(getRoleName(messageVO.getSenderRole()));
        messageVO.setReceiverRoleName(getRoleName(messageVO.getReceiverRole()));

        // 如果是回复消息，获取原消息信息
        if (messageVO.getReplyToId() != null) {
            MessageVO replyMessage = messageMapper.selectMessageDetail(messageVO.getReplyToId());
            if (replyMessage != null) {
                // 避免无限递归，只处理基本信息
                replyMessage.setTimeAgo(formatTimeAgo(replyMessage.getCreatedAt()));
                replyMessage.setSenderRoleName(getRoleName(replyMessage.getSenderRole()));
                replyMessage.setReceiverRoleName(getRoleName(replyMessage.getReceiverRole()));
                messageVO.setReplyMessage(replyMessage);
            }
        }

        return messageVO;
    }

    /**
     * 格式化时间为"多久之前"的形式
     * @param dateTime 时间
     * @return 格式化后的字符串
     */
    private String formatTimeAgo(LocalDateTime dateTime) {
        if (dateTime == null) {
            return "";
        }

        LocalDateTime now = LocalDateTime.now();
        long seconds = now.toEpochSecond(ZoneOffset.UTC) - dateTime.toEpochSecond(ZoneOffset.UTC);

        if (seconds < 60) {
            return "刚刚";
        } else if (seconds < 3600) {
            return seconds / 60 + "分钟前";
        } else if (seconds < 86400) {
            return seconds / 3600 + "小时前";
        } else if (seconds < 604800) {
            return seconds / 86400 + "天前";
        } else {
            return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        }
    }
    @Override
    public MessageVO getMessageDetail(Long messageId, Long userId) {
        // 1. 获取消息详情
        MessageVO messageVO = messageMapper.selectMessageDetail(messageId);

        // 2. 验证消息是否存在
        if (messageVO == null) {
            throw new RuntimeException("消息不存在");
        }

        // 3. 验证用户是否有权限查看该消息
        if (!messageVO.getSenderId().equals(userId) && !messageVO.getReceiverId().equals(userId)) {
            throw new RuntimeException("无权查看该消息");
        }

        // 4. 如果当前用户是接收者且消息未读，则标记为已读
        if (messageVO.getReceiverId().equals(userId) && !messageVO.getIsRead()) {
            markAsRead(messageId, userId);
            messageVO.setIsRead(true);
        }

        // 5. 获取回复消息（查询所有reply_to_id = messageId的消息）
        List<MessageVO> replies = messageMapper.selectRepliesByMessageId(messageId);
        if (replies != null && !replies.isEmpty()) {
            // 处理每条回复消息
            replies = replies.stream()
                    .map(this::processMessageVO)
                    .collect(Collectors.toList());
            messageVO.setReplies(replies);
        }

        // 6. 处理消息，填充额外信息
        return processMessageVO(messageVO);
    }

    /**
     * 获取角色名称
     * @param role 角色编码
     * @return 角色名称
     */
    private String getRoleName(Long role) {
        if (role == null) {
            return "";
        }

        switch (role.intValue()) {
            case 1:
                return "管理员";
            case 2:
                return "教师";
            case 3:
                return "家长";
            default:
                return "未知";
        }
    }
}